//
//  CALayer+Tool.m
//  JinXun
//
//  Created by Apple on 2022/1/15.
//

#import "CALayer+Tool.h"

@implementation CALayer (Tool)

+ (CALayer *)gradualLayerWithColors:(NSArray <UIColor *> *)colors vierticalOrHorizontal:(BOOL)vertical frame:(CGRect)frame
{
    CALayerGradientColorType type = vertical ? CALayerGradientColorType_TopToBottom : CALayerGradientColorType_LeftToRight;
    return [self gradualLayerWithColors:colors frame:frame type:type];
}

+ (CALayer *)gradualLayerWithColors:(NSArray <UIColor *> *)colors frame:(CGRect)frame type:(CALayerGradientColorType)type
{
    
    CGPoint startPoint = CGPointMake(0, 0);
    CGPoint endPoint = CGPointMake(0, 0);

    switch (type) {
        case CALayerGradientColorType_TopToBottom:
            startPoint = CGPointMake(0, 0);
            endPoint = CGPointMake(0, 1);
            break;
        case CALayerGradientColorType_LeftToRight:
            startPoint = CGPointMake(0, 0);
            endPoint = CGPointMake(1, 0);
            break;
        case CALayerGradientColorType_LeftTopToRightBottom:
            startPoint = CGPointMake(0, 0);
            endPoint = CGPointMake(1, 1);
            break;
        case CALayerGradientColorType_LeftBottomToRightTop:
            startPoint = CGPointMake(0, 1);
            endPoint = CGPointMake(1, 0);
            break;

        default:
            break;
    }
    
    return [self gradualLayerWithColors:colors frame:frame startPoint:startPoint endPoint:endPoint];
}


+ (CALayer *)gradualLayerWithColors:(NSArray <UIColor *>*)colors frame:(CGRect)frame startPoint:(CGPoint)startPoint endPoint:(CGPoint)endPoint
{
    NSMutableArray *cgColors = [@[] mutableCopy];
    [colors enumerateObjectsUsingBlock:^(UIColor * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [cgColors addObject:(__bridge id)obj.CGColor];
    }];
    
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.name = @"color";
    gradientLayer.bounds = frame;
    gradientLayer.borderWidth = 0;
    gradientLayer.frame = frame;
    gradientLayer.colors = cgColors;
    gradientLayer.startPoint = startPoint;
    gradientLayer.endPoint = endPoint;

    return gradientLayer;
}


@end
